import time
import functools
import logging
from typing import Dict, Any, Optional, Callable
from config import Config

logger = logging.getLogger(__name__)

def monitor_function(name: str = None, metadata: Dict[str, Any] = None):
    """监控函数执行性能的装饰器"""
    def decorator(func: Callable):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            if not Config.MONITORING_ENABLED:
                return func(*args, **kwargs)
            
            func_name = name or func.__name__
            start_time = time.time()
            
            try:
                # 执行函数
                result = func(*args, **kwargs)
                
                # 计算执行时间
                execution_time = (time.time() - start_time) * 1000  # 转换为毫秒
                
                # 记录性能日志
                logger.info(f"函数执行完成: {func_name}, 执行时间: {execution_time:.2f}ms")
                
                # 检查是否超过慢查询阈值
                if execution_time > Config.SLOW_QUERY_THRESHOLD_MS:
                    logger.warning(f"慢查询警告: {func_name} 执行时间 {execution_time:.2f}ms")
                
                return result
                
            except Exception as e:
                execution_time = (time.time() - start_time) * 1000
                logger.error(f"函数执行失败: {func_name}, 错误: {e}, 执行时间: {execution_time:.2f}ms")
                raise
        
        return wrapper
    return decorator

def monitor_rag_query(collection_name: str = None):
    """监控 RAG 查询的装饰器"""
    def decorator(func: Callable):
        @functools.wraps(func)
        async def wrapper(*args, **kwargs):
            if not Config.MONITORING_ENABLED:
                return await func(*args, **kwargs)
            
            start_time = time.time()
            
            try:
                # 执行 RAG 查询
                result = await func(*args, **kwargs)
                
                # 计算响应时间
                response_time = (time.time() - start_time) * 1000
                
                # 记录RAG查询日志
                logger.info(f"RAG查询完成, 响应时间: {response_time:.2f}ms")
                
                return result
                
            except Exception as e:
                response_time = (time.time() - start_time) * 1000
                logger.error(f"RAG 查询失败: {e}, 响应时间: {response_time:.2f}ms")
                raise
        
        return wrapper
    return decorator

def monitor_document_upload(collection_name: str = None):
    """监控文档上传的装饰器"""
    def decorator(func: Callable):
        @functools.wraps(func)
        async def wrapper(*args, **kwargs):
            if not Config.MONITORING_ENABLED:
                return await func(*args, **kwargs)
            
            start_time = time.time()
            
            try:
                # 执行文档上传
                result = await func(*args, **kwargs)
                
                # 计算处理时间
                processing_time = (time.time() - start_time) * 1000
                
                # 记录文档上传日志
                logger.info(f"文档上传完成, 处理时间: {processing_time:.2f}ms")
                
                return result
                
            except Exception as e:
                processing_time = (time.time() - start_time) * 1000
                logger.error(f"文档上传失败: {e}, 处理时间: {processing_time:.2f}ms")
                raise
        
        return wrapper
    return decorator

def monitor_model_generation(model_name: str = None):
    """监控模型生成的装饰器"""
    def decorator(func: Callable):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            if not Config.MONITORING_ENABLED:
                return func(*args, **kwargs)
            
            start_time = time.time()
            
            try:
                # 执行模型生成
                result = func(*args, **kwargs)
                
                # 计算生成时间
                generation_time = (time.time() - start_time) * 1000
                
                # 记录模型生成日志
                logger.info(f"模型生成完成, 生成时间: {generation_time:.2f}ms")
                
                return result
                
            except Exception as e:
                generation_time = (time.time() - start_time) * 1000
                logger.error(f"模型生成失败: {e}, 生成时间: {generation_time:.2f}ms")
                raise
        
        return wrapper
    return decorator

def monitor_api_endpoint(endpoint_name: str = None):
    """监控 API 端点的装饰器"""
    def decorator(func: Callable):
        @functools.wraps(func)
        async def wrapper(*args, **kwargs):
            if not Config.MONITORING_ENABLED:
                return await func(*args, **kwargs)
            
            endpoint = endpoint_name or func.__name__
            start_time = time.time()
            
            try:
                # 执行 API 端点
                result = await func(*args, **kwargs)
                
                # 计算响应时间
                response_time = (time.time() - start_time) * 1000
                
                # 记录API调用日志
                logger.info(f"API调用完成: {endpoint}, 响应时间: {response_time:.2f}ms")
                
                return result
                
            except Exception as e:
                response_time = (time.time() - start_time) * 1000
                logger.error(f"API 端点失败: {endpoint}, 错误: {e}, 响应时间: {response_time:.2f}ms")
                raise
        
        return wrapper
    return decorator 